
package com.jf.cloud.user.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.jf.cloud.api.platform.feign.ConfigFeignClient;
import com.jf.cloud.api.platform.vo.ScoreExpireConfigVO;
import com.jf.cloud.common.constant.ConfigNameConstant;
import com.jf.cloud.common.util.Json;
import com.jf.cloud.user.service.UserExtensionService;
import com.jf.cloud.user.service.UserLevelService;
import com.jf.cloud.user.service.UserScoreGetLogService;
import com.jf.cloud.user.service.UserService;
import com.jf.cloud.user.vo.UserVO;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author zz
 * @date 2021-07-22 16:38:42
 */
@Component
public class ScoreTask {

    private static final Logger log = LoggerFactory.getLogger(ScoreTask.class);

    @Autowired
    private UserExtensionService userExtensionService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserLevelService userLevelService;
    @Autowired
    private UserScoreGetLogService userScoreGetLogService;
    @Autowired
    private ConfigFeignClient configFeignClient;

    /**
     * 将会员设为已过期状态
     * 付费会员过期处理规则：
     * 将付费会员的等级和类型变成
     *
     */
    @XxlJob("vipUserClear")
    public void vipUserClear() {
        log.info("将会员设为已过期状态》》》》》》》》》》》》》》》》》》》》》");
        // 获取截至日期之前的所有付费会员信息
        List<UserVO> users = userService.selectMemberByEndTime(DateUtil.endOfDay(DateUtil.yesterday()));
        if (CollectionUtil.isEmpty(users)) {
            log.info("将会员设为已过期状态》》》》》》》》》》》》》》》》》》》》》");
            return;
        }
        // 会员过期变更规则：将付费会员变成普通会员，会员等级直接变成普通会员的成长值对应的等级
        userLevelService.expireVipUsers(users);

        log.info("将会员设为已过期状态》》》》》》》》》》》》》》》》》》》》》");
    }
    /**
     * 积分过期定时任务
     */
    @XxlJob("scoreExpireTask")
    public void scoreExpireTask() {
        // 0.计算过期时间
        String scoreExpireParam = configFeignClient.getConfig(ConfigNameConstant.SCORE_EXPIRE).getData();
        //计算过期时间
        ScoreExpireConfigVO scoreExpireParamConfigVO = Json.parseObject(scoreExpireParam, ScoreExpireConfigVO.class);
        if(Objects.isNull(scoreExpireParamConfigVO) || !scoreExpireParamConfigVO.getScoreExpireSwitch()){
            return;
        }
        int year = scoreExpireParamConfigVO.getExpireYear() - 1;
        DateTime dateTime = DateUtil.offset(DateUtil.beginOfDay(new Date()), DateField.YEAR, -year);
        // 1.修改用户过期积分
        userScoreGetLogService.updateExpireScoreDetail(dateTime);
    }
}
